import React, { FC, useCallback, useState } from "react";
import { Button, Modal, message as antMessage } from "antd";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import { BaseButtonProps } from "antd/es/button/button";
export interface ButtonConfirm extends BaseButtonProps {
  title?: string;
  request: () => Promise<Record<string, any>>;
  icon?: React.ReactNode;
  okText?: string;
  cancelText?: string;
  content?: string;
  message?: string;
  confirm?: boolean;
  buttonText?: string;
  onSuccess?: () => void;
}
const ButtonConfirm: FC<ButtonConfirm> = (props) => {
  const {
    title = "是否删除",
    request,
    icon = <ExclamationCircleOutlined />,
    okText = "确定",
    cancelText = "取消",
    content = "",
    message,
    confirm = true,
    buttonText = "",
    onSuccess,
    ...otherProps
  } = props;
  const [loading, setLoading] = useState(false);
  const onOk = useCallback(async () => {
    setLoading(true);
    try {
      const res = await request?.();
      if (res) {
        const { code, data } = res || {};
        if (code === 0) {
          if (message) {
            antMessage.success(message);
          } else {
            antMessage.success(`${buttonText}操作成功`);
          }
          onSuccess?.();
        }
      }
    } finally {
      setLoading(false);
    }
  }, [request, onSuccess, message, buttonText]);
  const onClick = useCallback(() => {
    if (confirm) {
      Modal.confirm({
        title,
        icon,
        content,
        okText,
        cancelText,
        onOk: () => {
          onOk();
        },
      });
    } else {
      onOk?.();
    }
  }, [title, icon, okText, confirm, onOk, cancelText, content]);
  return (
    <Button loading={loading} onClick={onClick} {...otherProps}>
      {buttonText}
    </Button>
  );
};
export default ButtonConfirm;
